package com.qin.handler;

import com.qin.protobuf.LogClientSendRespProto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.CharsetUtil;

/**
 * 客户端处理器
 *
 * @author qinxh
 * @date 2020/08/13
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        SocketChannel channel = (SocketChannel) ctx.channel();

        System.out.println(" ------> 信道激活报告开始");
        System.out.println("本客户端链接到服务端的channelId：" + channel.id());
        System.out.println("IP:" + channel.localAddress().getHostString());
        System.out.println("Port:" + channel.localAddress().getPort());
        System.out.println("信道激活报告完毕 <------ ");
    }

    /**
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        System.out.println("断开链接：" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        //接收服务端发送过来的消息
        LogClientSendRespProto.LogClientSendResp req = (LogClientSendRespProto.LogClientSendResp) msg;
        System.out.println("收到服务端 [" + ctx.channel().remoteAddress() + " ] 的消息：" + req.toString());
    }
}
